/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAOpeningHoursDetailsViewController.m
//  redia-bapps-ios
//
//  Created by Mads Darø Kristensen on 10/7/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAOpeningHoursDetailsViewController.h"
#import "BAFlyoutMenuViewController.h"
#import "BAUtils.h"
#import "BAOpeningHoursInterval.h"
#import "BAOpeningHoursDay.h"
#import "BAOpeningHoursCell.h"
#import "BAOpeningHoursTopCell.h"

@interface BAOpeningHoursDetailsViewController (){
    NSInteger selectedIndex;
}

@property (nonatomic, strong) NSArray* openingHoursCells;
@property (nonatomic, strong) BAOpeningHoursTopCell* topCell;
@property (nonatomic, strong) NSDate* lastLoadedDate;
@end

@implementation BAOpeningHoursDetailsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    selectedIndex = -1;
    // Do any additional setup after loading the view from its nib.
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault)

    if (self.library) {
        NSMutableArray* openingHoursCells = [NSMutableArray new];
        _topCell = [[[NSBundle mainBundle] loadNibNamed:@"BAOpeningHoursTopCell" owner:self options:nil] objectAtIndex:0];
        [self.topCell setLibrary:self.library];
        
        NSArray* dayKeys = @[@"mon",@"tue",@"wed",@"thu",@"fri",@"sat",@"sun"];
        NSDictionary* dayKeyToDayNameDict = @{@"mon":@"Mandag",@"tue":@"Tirsdag",@"wed":@"Onsdag",@"thu":@"Torsdag",@"fri":@"Fredag",@"sat":@"Lørdag",@"sun":@"Søndag"};
        bool discloseButtonNeeded = false;
        int i = 0;
        for (NSString* dayKey in dayKeys) {
            BAOpeningHoursCell* cell = [[[NSBundle mainBundle] loadNibNamed:@"BAOpeningHoursCell" owner:self options:nil] objectAtIndex:0];
            BAOpeningHoursDay* day = [self.library.openingHours.days objectForKey:dayKey];
            [cell setDay:day];
            [cell setDayName:[dayKeyToDayNameDict objectForKey:dayKey]];
            [cell setIndex:i++];
            [openingHoursCells addObject:cell];
            
            BAOpeningHoursInterval* firstInterval = [day.intervals count]>0 ? [day.intervals objectAtIndex:0] : nil;

            if (day.intervals.count > 1 || firstInterval.note.length > 0) {
                discloseButtonNeeded = true;
            }
        }
        self.openingHoursCells = [NSArray arrayWithArray:openingHoursCells];

        for (BAOpeningHoursCell* cell in self.openingHoursCells) {
            [cell keepSpaceForDiscloseButton:discloseButtonNeeded];
        }
        self.lastLoadedDate = [NSDate date];
        
    } else {
        DLog(@"warning: opening hours details opened without library object");
    }
}

-(void)updateLabelFrom:(UILabel*)labelFrom labelTo:(UILabel*)labelTo day:(BAOpeningHoursDay*)day
{
    if (day==nil || [day.intervals count]==0) {
        return;
    }
    BAOpeningHoursInterval* interval = [day.intervals objectAtIndex:0];
    
    labelFrom.text = [NSString stringWithFormat:@"%02d:%02d", interval.open / 3600, (interval.open / 60) % 60];
    labelTo.text =   [NSString stringWithFormat:@"%02d:%02d", interval.close / 3600, (interval.close / 60) % 60];
    
    //note...
}

- (void)viewDidAppear:(BOOL)animated
{
    //FIXME: listen for global event when application is reactivated and refresh
    [super viewDidAppear:animated];
    [self enableUserInteraction];
    if (!RD_IS_IPAD) {
        //iphone only, refresh is handled differently on ipad
        if ([self.lastLoadedDate timeIntervalSinceNow] < -600) {
            //refresh at least every 10 minutes
            [self.navigationController popViewControllerAnimated:NO];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 1;
    }else{
        return [self.openingHoursCells count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return self.topCell;
    } else{
        return [self.openingHoursCells objectAtIndex:indexPath.row];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView beginUpdates];
    if (indexPath.section==0) {
        selectedIndex = -1;
        [tableView endUpdates];
        return;
    }
    BAOpeningHoursCell* cell = [self.openingHoursCells objectAtIndex:indexPath.row];
    /*
    if (cell.selectedHeight <= 49) {
        return;
    }
     */
    
    if (indexPath.row == selectedIndex) {
        
        [cell setSelected:NO];
        selectedIndex = -1;
        [tableView endUpdates];
    } else{
        selectedIndex = indexPath.row;
        [tableView endUpdates];
        
        CGRect rowrect = [tableView rectForRowAtIndexPath:indexPath];

        //DLog(@"row rect: %@", NSStringFromCGRect(rowrect));
        //DLog(@"table rect: %@", NSStringFromCGRect(tableView.bounds));
        
        if (rowrect.origin.y + rowrect.size.height > tableView.bounds.size.height) {
            [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }

    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 127;
    }
    
    if (indexPath.row == selectedIndex) {
        BAOpeningHoursCell* cell = [self.openingHoursCells objectAtIndex:indexPath.row];
        return cell.selectedHeight;
    } else{
        return 49;
    }
}


#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}

@end
